axios.defaults.baseURL = "https://mock.apipark.cn/m1/4730765-4383283-default"

//抽取提示信息
//showToast("xxxxxx")

function showToast(msg){
    const toastDom = document.querySelector(".my-toast")

    //实例化toast组件
    const toast = new bootstrap.Toast(toastDom)

    //修改内容
    document.querySelector(".toast-body").innerHTML = msg

    //显示
    toast.show()
}

//抽取校验函数（判断是否登录）

function checkLogin(){
    //获取token
    const token = localStorage.getItem("token")
    if (token == null) {
        showToast("非法访问，请先登录！")
        setTimeout(() => {
            location.href = "./login.html"
        }, 1500)
    }
}

// 抽取渲染函数（渲染缓存中的用户名）
function renderUserName(){
    const username = localStorage.getItem("username")
    document.querySelector(".username").innerHTML = username
}

//抽取退出登录函数
function registerLoginOut(){
    // 绑定点击事件
        document.querySelector('#logout').addEventListener('click',()=>{
    //     console.log(12345);
           localStorage.removeItem('token');
           localStorage.removeItem('username');
           location.href = './login.html'
        })
    }

//axios 拦截器 请求/响应
axios.interceptors.request.use(function (config) {
    config.headers["info"] = "hi"
    console.log(config);
    const token = localStorage.getItem("token")
    if (token) {
        config.headers["Authorization"] = token
    }
    return config
},
    function (error) {
    return Promise.reject(error)
})

axios.interceptors.response.use(function(response) {
    return response.data
},function(){
    //token失效
    if (error.response.status === 401) {
        //已过期 登出
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        showToast("请重新登陆")
        setTimeout(function() {
            location.href = "./login.html"
        }, 1500)
    }
    return Promise.reject(error)
})